package common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

/**
 * 实现文件读写
 * @author maojj
 *
 */
public class FileOperation
{
	/**
	 * 读文件
	 * @param filePath - 文件绝对路径
	 * @return 文件行数组
	 * @throws IOException 
	 */
	public static String[] read(String filePath) throws IOException
	{
		InputStream is = new FileInputStream(filePath);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		List<String> lines = new ArrayList<String>();
		String Line = null;
		while ((Line = reader.readLine()) != null)
		{
			if (!Line.isEmpty())  //忽略空行
			{
				lines.add(Line);
			}
		}
		reader.close();
		is.close();

		String[] ret = new String[lines.size()];
		lines.toArray(ret);
		return ret;
	}
	

	/**
	 * 将多行数据写入文件
	 * @param lines - 写入文件的数据
	 * @param filePath - 文件绝对路径
	 * @throws IOException 
	 */
	public static void write(String[] lines, String filePath) throws IOException
	{	
		File file = new File(filePath);
		//如果文件不存在，创建文件
		if (!file.exists())
		{
			file.createNewFile();
		}
		
		OutputStream os = new FileOutputStream(file, true);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
		for (String line : lines)
		{
			if (!line.isEmpty())  //忽略空行
			{
				writer.write(line + "\n");
			}
		}
		writer.close();
	}
	
	/**
	 * 将一行数据写入文件
	 * @param line - 写入文件的数据
	 * @param filePath - 文件绝对路径
	 * @throws IOException 
	 */
	public static void write(String line, String filePath) throws IOException
	{	
		File file = new File(filePath);
		OutputStream os;
		BufferedWriter writer;
		
		//如果文件不存在，创建文件
		if (!file.exists())
		{
			file.createNewFile();
		}
			
		os = new FileOutputStream(file, true);
		writer = new BufferedWriter(new OutputStreamWriter(os));
		if (!line.isEmpty())  //忽略空行
		{
			writer.write(line + "\n");
		}
		writer.close();
	}
	
	/**
	 * 删除文件
	 * @param filePath - 文件绝对路径
	 */
	public static void delete(String filePath)
	{
		File file = new File(filePath);
		if (file.exists())
		{
			file.delete();
		}	
	}
	
	/**
	 * 获取指定目录的文件名称列表
	 * @param dir - 目录绝对路径
	 * @param isIncludeSubdir - True，返回文件名称列表包含子目录文件；False，返回文件名称列表不包含子目录文件
	 * @return 文件名称列表
	 */
	public static String[] getFileByDir(String dir, boolean isIncludeSubdir)
	{
		File[] files = (new File(dir)).listFiles();
		List<String> fileList = new ArrayList<>();

		for (int i = 0; i < files.length; i++)
		{
			if (files[i].isFile())
			{
				fileList.add(files[i].getPath() + files[i].getName());
			}
			else if (files[i].isDirectory() && isIncludeSubdir)
			{
				String[] subFiles = getFileByDir(files[i].getPath(), isIncludeSubdir);
				for (String subFile : subFiles)
				{
					fileList.add(subFile);	
				}	
			}
		}
		String[] ret = new String[fileList.size()];
		return fileList.toArray(ret);
	}

	/**
	 * 下载Windows共享目录文件
	 * @param remotePath - 共享目录文件路径，如：172.3.207.26/logs/default2017-04-17.log.0
	 * @param account - 共享目录账号
	 * @param password - 共享目录密码
	 * @param localPath - 本地路径，用于保存共享文件，如：D:/logs
	 * @return 下载成功返回TRUE；失败返回FALSE
	 * @throws IOException
	 */
    public static Boolean getSmbFile(String remotePath, String remoteAccount, String remotePassword, String localPath) throws IOException
    {
    	Boolean ret = true;
    	InputStream in = null; 
    	OutputStream out = null; 
    	
    	String remoteIP = remotePath.split("/", 2)[0];
    	try {
    		NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(remoteIP, remoteAccount, remotePassword);
            SmbFile remoteFile = new SmbFile("smb://"+remotePath, auth);  
            String remoteFileName = remoteFile.getName();
            File localFile = new File(localPath + File.separator + remoteFileName);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));  
            out = new BufferedOutputStream(new FileOutputStream(localFile)); 
            byte[] buffer = new byte[1024];  
            while (in.read(buffer) != -1)
            {  
                out.write(buffer);  
                buffer = new byte[1024];  
            }
		}catch (Exception e) {
			//e.printStackTrace();
			ret = false;
		}
    	finally {
    		if (in != null)
    		{
    			in.close();
    		}
    		if (out != null)
    		{
    			out.close();
    		}
		}
    	return ret;
    }
    
    /**
     * 文件编码转换：GBK转UTF-8
     * @param srcFileName - 原文件绝对路径
     * @param destFileName - 目标文件绝对路径
     * @throws IOException
     */
	public static void transferGbkToUtf8(String srcFileName, String destFileName) throws IOException
	{
		String line_separator = System.getProperty("line.separator");
		FileInputStream fis = new FileInputStream(srcFileName);
		StringBuffer content = new StringBuffer();
		DataInputStream in = new DataInputStream(fis);
		BufferedReader d = new BufferedReader(new InputStreamReader(in, "GBK"));
		String line = null;
		while ((line = d.readLine()) != null)
		{
			content.append(line + line_separator);
		}
		d.close();
		in.close();
		fis.close();
		
		Writer ow = new OutputStreamWriter(new FileOutputStream(destFileName), "utf-8");
		ow.write(content.toString());
		ow.close();
	}
}
